package com.dlyk.service.impl;

import com.dlyk.constant.Constants;
import com.dlyk.manager.RedisManager;
import com.dlyk.mapper.TPermissionMapper;
import com.dlyk.mapper.TRoleMapper;
import com.dlyk.mapper.TUserMapper;
import com.dlyk.model.TPermission;
import com.dlyk.model.TRole;
import com.dlyk.model.TUser;
import com.dlyk.query.BaseQuery;
import com.dlyk.query.UserQuery;
import com.dlyk.service.UserService;
import com.dlyk.util.CacheUtils;
import com.dlyk.util.JWTUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: ajie
 * @date: 2024/7/5 21:59:51
 * @version: 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private TUserMapper tUserMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private TRoleMapper tRoleMapper;

    @Resource
    private RedisManager redisManager;

    @Resource
    private TPermissionMapper tPermissionMapper;

    /**
     * @description: 登录查询
     * @params: [username]       
     * @return: 
     * @author: ajie
     * @date: 2024/7/17 23:08
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        TUser tUser = tUserMapper.selectByLoginAct(username);
        if (tUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        //查询一下当前用户的角色
        List<TRole> tRoleList = tRoleMapper.selectByUserId(tUser.getId());
        //字符串的角色列表
        List<String> stringRoleList = new ArrayList<>();
        tRoleList.forEach(tRole -> stringRoleList.add(tRole.getRole()));

        tUser.setRoleList(stringRoleList);//设置用户的角色

        //查询一下该用户有哪些菜单权限
        List<TPermission> menuPermissionList = tPermissionMapper.selectMenuPermissionByUserId(tUser.getId());
        tUser.setMenuPermissionList(menuPermissionList);

        //查询一下该用户有哪些功能
        List<TPermission> buttonPermissionList = tPermissionMapper.selectButtonPermissionByUserId(tUser.getId());
        List<String> stringPermissionList = buttonPermissionList.stream().map(TPermission::getCode).toList();
        tUser.setPermissionList(stringPermissionList);//设置用户的权限标识符

        return tUser;
    }


    @Override
    public PageInfo<TUser> getUserByPage(Integer current) {
        //设置PageHelper的分页参数
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        //查询
        List<TUser> list = tUserMapper.selectUserByPage(BaseQuery.builder().build());
        //封装分页参数到PageInfo
        PageInfo<TUser> info = new PageInfo<>(list);
        return info;

    }

    @Override
    public TUser getUserById(Integer id) {
        return tUserMapper.selectDetailById(id);
    }

    @Override
    public int saveUser(UserQuery userQuery) {

        TUser tUser = new TUser();

        BeanUtils.copyProperties(userQuery,tUser);

        tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));//密码加密
        tUser.setCreateTime(new Date());//创建时间

        ///登陆人的id
        Integer loginUserId = JWTUtils.parseJWTByUserId(userQuery.getToken());
        tUser.setCreateBy(loginUserId);//创建人
        return tUserMapper.insertSelective(tUser);
    }

    @Override
    public int updateUser(UserQuery userQuery) {
        TUser tUser = new TUser();

        BeanUtils.copyProperties(userQuery,tUser);

        if (StringUtils.hasText(userQuery.getLoginPwd())){
            tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));//密码加密
        }
        tUser.setEditTime(new Date());//创建时间

        ///登陆人的id
        Integer loginUserId = JWTUtils.parseJWTByUserId(userQuery.getToken());
        tUser.setEditBy(loginUserId);//创建人
        return tUserMapper.updateByPrimaryKeySelective(tUser);
    }

    @Override
    public int delUserById(Integer id) {
        return tUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int batchDelUserByIds(List<String> idList) {
        return tUserMapper.deleteByIds(idList);
    }

    @Override
    public List<TUser> getOwnerList() {
        //从redis中查
        //redis查不到，就从数据库查，并且把数据放入redis（5分钟过期）
        return CacheUtils.getCacheData(()->{
            //生产者，从缓存redis中查询数据
            return (List<TUser>)redisManager.getValue(Constants.REDIS_OWNER_KEY);
        },()->{
            //生产者，从mysql中查询数据
            return tUserMapper.selectByOwner();
        },(t)->{
            redisManager.setValue(Constants.REDIS_OWNER_KEY,t);
        });
    }
}
